// pages/openbillbox/addgoods/addgoods.js
import {
  _upImgUrl,
} from '../../../utils/config.js'
import {
  errorMsg
} from '../../../utils/tool.js'
import {
  textToShopinfo,
  textToAddressInfo,
  createInviteCode,
  getToken
} from '../../../utils/networkRequest.js'
var app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    sellerInfo: null,
    isAdd: false,
    imgSrc: "",
    imgId: "",
    images: [],
    name: "", //商品名称
    remark: "", //商品备注
    count: 1, //商品数量
    price: "", //商品价格
    text: "", //自动识别文字
    // customItem: '请选择',
    timestamp:"", //上传图片时间戳
    isShowPla: true,

    shouName: "",
    shouPhone: "",
    shouShenShiQu: [],
    shouAddress: "",
    shouText: "",
    isChangeGoods: false,
    changeGoodsInfo: null,
    changeGoodsIndex: "",
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    let self = this;







    if (options.shouAddressInfo) {
      let shouAddressInfo = JSON.parse(options.shouAddressInfo);
      if (shouAddressInfo.address) {
        this.setData({
          sellerInfo: JSON.parse(unescape(options.item)),
          isAdd: options.isAdd ? options.isAdd : false,
          shouName: shouAddressInfo.name,
          shouPhone: shouAddressInfo.phone,
          shouShenShiQu: shouAddressInfo.shenShiQu,
          shouAddress: shouAddressInfo.address,
          isShowPla: false,
          iscopy: options.iscopy
        })
      } else {
        this.setData({
          sellerInfo: JSON.parse(unescape(options.item)),
          isAdd: options.isAdd ? options.isAdd : false,
          shouName: shouAddressInfo.name,
          shouPhone: shouAddressInfo.phone,
          shouShenShiQu: shouAddressInfo.shenShiQu,
          shouAddress: shouAddressInfo.address,
          iscopy: options.iscopy
        })
      }

    } else {

      if (options.shareid) {
        wx.setNavigationBarTitle({
          title: '快速下单',
        })
        // 登录 
        wx.login({
          success: lr => {
            getToken(lr.code, (tr) => {
              if (tr.code == 0) {
                // wx.setStorage({ //将SessionInfo 放入本地缓存
                //   key: 'token',
                //   data: tr.data,
                // })

                // try {
                wx.setStorageSync('token', tr.data)
                // } catch (e) { }

                createInviteCode(options.shareid, (r) => {
                  if (r.code == 0) {
                    self.setData({
                      sellerInfo: r.data,
                      isAdd: options.isAdd ? options.isAdd : false,
                    })
                  }
                })
              }
            })
          }
        })

      } else {
        this.setData({
          sellerInfo: JSON.parse(unescape(options.item)),
          isAdd: options.isAdd ? options.isAdd : false,
        })
      }



    }


    if (options.changeGoodsInfo) {
      let changeGoodsInfo = JSON.parse(unescape(options.changeGoodsInfo))
      this.setData({
        isChangeGoods: true,
        imgSrc: changeGoodsInfo.imgSrc,
        imgId: changeGoodsInfo.imgId,
        images:changeGoodsInfo.images,
        timestamp:changeGoodsInfo.timestamp,
        name: changeGoodsInfo.name, //商品名称
        remark: changeGoodsInfo.remark, //商品备注
        count: changeGoodsInfo.count, //商品数量
        price: changeGoodsInfo.price, //商品价格
        changeGoodsInfo: changeGoodsInfo,
        changeGoodsIndex: options.changeGoodsIndex
      })
    }


  },

  editTotalReamrk: function() {
    let {
      remark
    } = this.data
    wx.navigateTo({
      url: '../totalremark/totalremark?totalRemark=' + remark,
    })
  },
  //下一步 
  goNext: function() {
    let {
      name,
      remark,
      count,
      price,
      imgSrc,
      imgId,
      images,
      timestamp,
      sellerInfo,
      isAdd,
      shouName,
      shouPhone,
      shouShenShiQu,
      shouAddress,
      isChangeGoods,
      changeGoodsIndex,
      changeGoodsInfo
    } = this.data; 
    let shouAddressInfo = {
      name: shouName,
      phone: shouPhone,
      shenShiQu: shouShenShiQu,
      address: shouAddress
    }

    let goodsInfo = {
      name: name,
      remark: remark,
      count: count,
      price: price,
      imgSrc: imgSrc,
      imgId: imgId,
      images:images,
      timestamp:timestamp
    }
    if (name == "") {
      errorMsg("请输入商品名称")
    } else if (count == "") {
      errorMsg("请输入商品数量")
    } else if (!isAdd && shouName == "") {
      errorMsg("请输入收件人姓名")
    } else if (!isAdd && !/^1([358][0-9]|4[579]|66|7[0135678]|9[89])[0-9]{8}$/.test(shouPhone)) {
      errorMsg("收件人手机号格式不正确")
    } else if (!isAdd && (!shouShenShiQu[0] || !shouShenShiQu[1] || !shouShenShiQu[2])) {
      errorMsg("请选择省市区")
    } else if (!isAdd && shouAddress == "") {
      errorMsg("请输入收件人详细地址")
    } else {

      if (isAdd) {
        var pages = getCurrentPages();
        var prevPage = pages[pages.length - 2]; //上一个页面 
        //直接调用上一个页面的setData()方法，把数据存到上一个页面中去  

        if (isChangeGoods) {
          prevPage.data.goodsList[changeGoodsIndex] = goodsInfo
          prevPage.setData({
            goodsList: prevPage.data.goodsList
          })

        } else {
          prevPage.data.goodsList.push(goodsInfo);
          prevPage.setData({
            goodsList: prevPage.data.goodsList
          })
        }



        wx.navigateBack();
      } else {
        wx.redirectTo({
          url: '../openbill/openbill?goodsInfo=' + escape(JSON.stringify(goodsInfo)) + '&sellerInfo=' + JSON.stringify(sellerInfo) + "&shouAddressInfo=" + JSON.stringify(shouAddressInfo) + "&addProduct=false",
        })
      }
    }
  },
  //继续添加
  addProduct: function() {
    let self = this;
    let {
      name,
      remark,
      count,
      price,
      imgSrc,
      imgId,
      images,
      timestamp,
      sellerInfo,
      isAdd,
      shouName,
      shouPhone,
      shouShenShiQu,
      shouAddress
    } = this.data;


    let shouAddressInfo = {
      name: shouName,
      phone: shouPhone,
      shenShiQu: shouShenShiQu,
      address: shouAddress
    }

    let goodsInfo = {
      name: name,
      remark: remark,
      count: count,
      price: price,
      imgSrc: imgSrc,
      imgId: imgId,
      images,images,
      timestamp:timestamp,
    }
    if (name == "") {
      errorMsg("请输入商品名称")
    } else if (count == "") {
      errorMsg("请输入商品数量")
    } else if (!isAdd && shouName == "") {
      errorMsg("请输入收件人姓名")
    } else if (!isAdd && !/^1([358][0-9]|4[579]|66|7[0135678]|9[89])[0-9]{8}$/.test(shouPhone)) {
      errorMsg("收件人手机号格式不正确")
    } else if (!isAdd && (!shouShenShiQu[0] || !shouShenShiQu[1] || !shouShenShiQu[2])) {
      errorMsg("请选择省市区")
    } else if (!isAdd && shouAddress == "") {
      errorMsg("请输入收件人详细地址")
    } else {
      if (isAdd) {
        var pages = getCurrentPages();
        var prevPage = pages[pages.length - 2]; //上一个页面 
        //直接调用上一个页面的setData()方法，把数据存到上一个页面中去  
        prevPage.data.goodsList.push(goodsInfo);
        prevPage.setData({
          goodsList: prevPage.data.goodsList
        })

        // self.setData({
        //   sellerInfo: prevPage.data.sellerInfo,
        // }) 
        wx.redirectTo({
          url: '../addgoods/addgoods?item=' + JSON.stringify(prevPage.data.sellerInfo) + '&isAdd=true'
        })
      } else {

        wx.redirectTo({
          url: '../openbill/openbill?goodsInfo=' + escape(JSON.stringify(goodsInfo)) + '&sellerInfo=' + JSON.stringify(sellerInfo) + "&shouAddressInfo=" + JSON.stringify(shouAddressInfo) + "&addProduct=true",
        })

      }
    }

  },
  //获取自动识别文字
  getText: function(e) {
    this.setData({
      text: e.detail.value
    })
  },
  //清空
  textClear: function() {
    this.setData({
      text: ""
    })
  },
  //获取商品名称
  getName: function(e) {
    this.setData({
      name: e.detail.value
    })
  },
  //获取规格
  getRemark: function(e) {
    this.setData({
      remark: e.detail.value
    })
  },
  //获取数量
  getCount: function(e) {
    this.setData({
      count: e.detail.value
    })
  },
  //获取价格
  getPrice: function(e) {
    this.setData({
      price: e.detail.value
    })
  },

  //自动识别文字
  textToShopinfo: function() {
    let self = this;
    let {
      text
    } = this.data;
    if (text == "") {
      errorMsg("请先粘贴商品信息")
    } else {
      textToShopinfo(text, (r) => {
        console.log(r);
        if (r.code == 0) {
          self.setData({
            name: r.data.name,
            remark: r.data.memo,
            count: r.data.count,
            price: r.data.price
          })
        } else {
          errorMsg(r.message)
        }
      })
    }

  },
  creates: function() {


  },
  //上传图片
  uploadImg: function() {

    let token = null;
    try {
      var value = wx.getStorageSync('token') //从本地缓存中获取Session信息 
      if (value) {
        token = value.token;
      }
    } catch (e) {

    }

    let defaluteHeader = {
      'content-type': 'application/json',
    }

    if (token) { //如果token存在把他放入头部
      defaluteHeader = {
        'content-type': 'application/json',
        'Authorization': "Bearer " + token,
      }
    }


    let self = this;
    let timps = Date.parse(new Date());
    wx.chooseImage({
      count: 9,
      success(res) {
        const tempFilePaths = res.tempFilePaths
        // wx.uploadFile({
        //   url: _upImgUrl, //仅为示例，非真实的接口地址
        //   filePath: tempFilePaths[0],
        //   header: defaluteHeader,
        //   name: 'image',
        //   success(res) {
        //     let r = JSON.parse(res.data)
        //     if (r.code == 0) {
        //       debugger;
        //       self.setData({
        //         imgSrc: r.data.url,
        //         imgId: r.data.id
        //       })
        //     } else {
        //       errorMsg(r.message)
        //     }
        //   }
        // })

        app.uploadimg({
          url: _upImgUrl, //这里是你图片上传的接口
          path: tempFilePaths, //这里是选取的图片的地址数组  
          header: defaluteHeader,
          name: 'image',
          prams: {
            timestamp: timps
          } 
        }, function(r) {

          //图片上传完之后 提交表单  
          // buyersubaftersale(id, remark, name, mobile, address, expno, e.detail.formId, token, (r) => {
          //   if (r.code == 0) {
          //     wx.redirectTo({
          //       url: '../aftersalesubsuccess/aftersalesubsuccess',
          //     })
          //   } else {
          //     errorMsg(r.message)
          //   }
          // })
          self.setData({
            imgSrc: tempFilePaths[0],
            imgId: r.data.id,
            images: tempFilePaths,
            timestamp: timps
          })

        }.bind(this))

      }
    })
  },

  //获取收件人姓名
  getShouName: function(e) {
    this.setData({
      shouName: e.detail.value
    })
  },
  //获取收件人电话
  getShouPhone: function(e) {
    this.setData({
      shouPhone: e.detail.value
    })
  },
  //获取收件人所在省市区
  getShouShenShiQu: function(e) {
    this.setData({
      shouShenShiQu: e.detail.value
    })
  },
  //获取收件人详细地址
  getShouAddress: function(e) {
    if (e.detail.value) {
      this.setData({
        shouAddress: e.detail.value,
        isShowPla: false,
      })
    } else {
      this.setData({
        shouAddress: e.detail.value
      })
    }
  },
  getShouAddressBlur: function() {
    if (this.data.shouAddress) {
      this.setData({
        isShowPla: false
      })
    } else {
      this.setData({
        isShowPla: true
      })
    }

  },
  getShouAddressFocus: function() {

    this.setData({
      isShowPla: false
    })

  },
  //获取自动识别文字
  getShouText: function(e) {
    this.setData({
      shouText: e.detail.value
    })
  },
  //清空
  textShouClear: function() {
    this.setData({
      shouText: ""
    })
  },
  //自动识别地址信息自动拆封
  textToAddressInfo: function() {
    let self = this;
    let {
      shouText
    } = this.data;
    if (shouText == "") {
      errorMsg("请先粘贴地址信息")
    } else {
      textToAddressInfo(shouText, (r) => {
        console.log(r);
        if (r.code == 0) {
          self.setData({
            shouName: r.data.name,
            shouPhone: r.data.mobile,
            shouShenShiQu: r.data.p_c_b,
            shouAddress: r.data.address,
            isShowPla: false
          })
        } else {
          errorMsg(r.message)
        }
      })
    }

  },

  bindRegionChange: function(e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      shouShenShiQu: e.detail.value
    })
  }
})